package com.me.chat.ws;

import com.alibaba.fastjson.JSON;
import com.me.chat.mq.sender.WsChatSender;
import com.me.chat.pojo.chat.ChatMessage;
import com.me.chat.pojo.chat.MessageType;
import com.me.chat.pojo.chat.qo.ChatLatelyQO;
import com.me.chat.pojo.chat.qo.ChatMessageQO;
import com.me.chat.service.chat.ChatLateService;
import com.me.chat.service.chat.ChatMessageService;
import com.me.chat.util.CommonUtil;
import com.me.chat.util.SimpleUserInfo;
import com.me.chat.util.stauts.MessageCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;


/**
 * @Authhor: qiu
 * @Date: 2021/11/14 6:16 下午
 * 面向一对组的通讯方式 组可选择一对一与一对多
 */

@Component
@ServerEndpoint(value = "/chat/{token}")
@Slf4j
public class ChatWsServer {

    // 用户信息获取
    private static SimpleUserInfo simpleUserInfo;

    //mq topic分发
    private static WsAction wsAction;

    @Autowired
    public void getApplicationContext(SimpleUserInfo simpleUserInfo) {
        ChatWsServer.simpleUserInfo = simpleUserInfo;
    }

    @Autowired
    public void getApplicationContext(WsAction wsAction) {
        ChatWsServer.wsAction = wsAction;
    }

    //正常连接后触发
    @OnOpen
    public void wsOpen(Session session,@PathParam("token") String token) throws IOException {

        try {
            String userId = simpleUserInfo.getUserId(token);

            //ws连接的时候，userId 存入Map中，用于后续分发
            WsSessionData.sessionMap.put(userId,session);

            log.info("userId："+userId+" websocket 连接成功");
        }catch (InvalidTokenException e) {
            log.error("token 失效");
            //封装消息体
            MessageType messageType = new MessageType(MessageCode.NOACCESS,"token 失效 建立连接失败");
            String msgJson = JSON.toJSONString(messageType);
            session.getBasicRemote().sendText(msgJson);
            //关闭当前连接
            session.close();
        }
    }

    //受到信息后 转发
    @OnMessage
    public void receiveMessage(Session senderSession, String message,@PathParam("token")String token){
        wsAction.doAction(senderSession, message, token);
    }


    //连接断开后触发，从集合中删除用户连接的session
    @OnClose
    public void wsClose(Session session,@PathParam("token")String token) {
        String sender = simpleUserInfo.getUserId(token);
        WsSessionData.sessionMap.remove(sender);
        log.info(" 关闭了websocket连接");
    }

    //出现消息传输异常错误
    @OnError
    public void wsError(Session session, Throwable throwable) throws IOException {

        //当用户关闭浏览器则从集合中删除session
        log.error("与客户端 session id=" + session.getId() + " 通信错误..."+throwable.toString());
    }

}
